package com.zhn.usermanager.service.impl;

import com.zhn.usermanager.mapper.LoginMapper;
import com.zhn.usermanager.mapper.UserMapper;
import com.zhn.usermanager.pojo.User;
import com.zhn.usermanager.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl {

    @Resource
    private LoginMapper loginMapper;

    public Map<String, Object> login(UserVO userVO, HttpSession session){
        Map<String, Object> map = new HashMap<>();
        map.put("code", 601);
        map.put("msg", "用户名或者密码错误!");

        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        System.out.println(user);

        User return_user = loginMapper.login(user.getUsername());
        if(return_user != null && return_user.getPassword().equals(user.getPassword())) {
            map.put("code", 601);
            map.put("msg", "该账户未激活!");
            if (return_user.getAction() != 0){
                map.put("code", 200);
                map.put("msg", "登录成功!");
                map.put("data", return_user);
                session.setAttribute("user", return_user);

//                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                user.setLastlogintime(new Date());
                loginMapper.updateByUserName(user);

            }
        }
        return map;
    }
}
